import string

# Parse the machine-readable plaintext format from the MRT tool route_btoa
class BasicUpdate:

    def __init__ (self, line):

        # Fields for all updates
        self.time = 0
        self.type = None
        self.peer_ip = None
        self.peer_as = None
        self.prefix = []
        
        # Announcement-specific fields
        self.as_path = []
        
        line = string.strip(line)
        # Split the line into a list
        data = string.split(line, '|')

        try:
            assert ((data[1] == 'W' and len(data) == 5) or (data[1] == 'A'  and len(data) == 6))
        except:
            print "problem with following data: "
            print data
            raise

        # We must have these fields for either type
        self.time = int(data[0])    # Timestamps only have a 1 second granularity, so they are int.
        self.type = data[1]
        self.peer_ip = data[2]
        self.peer_as = data[3]

        if len(data) == 5: #withdrawal
            self.prefix = string.split(data[4], ' ')    # A list of prefixes

        if len(data) == 6: #announce
            self.prefix = string.split(data[4], ' ')    # A list of prefixes
	    for peer in string.split(data[5], ' '): #remove adjacent duplicates, put result in self.as_path
		if len(self.as_path) == 0:
		    self.as_path.append(peer)
		elif peer == self.as_path[-1]:
		    continue
		else:
		   self.as_path.append(peer) 

    def __str__(self):
	s = string.join([str(self.time), self.type, self.peer_ip, self.peer_as], '|')
	if self.type == 'A':
	    s = string.join([s, string.join(self.prefix), string.join(self.as_path)], '|')
	elif self.type == 'W':
	    s = string.join([s, string.join(self.prefix)], '|')
	return s 
